package net.pimpas.report.processor.common;

import net.pimpas.report.processor.exception.CommonProcessorException;
import net.pimpas.report.processor.exception.FieldValidationException;
import net.pimpas.report.processor.field.Field;
import net.pimpas.report.processor.resolver.FieldPropertyResolver;
import net.pimpas.report.processor.tree.node.Node;
import net.pimpas.report.processor.util.ProcessorUtils;
import net.pimpas.util.reflection.ReflectionUtil;

public abstract class AbstractCommonProcessor<T,X,Y extends CommonProcessorException> implements CommonProcessor<T, X, Y> {
	
	private T type;
	private Field field;
	
	public AbstractCommonProcessor(Field field, T type) {
		this.setField(field);
		this.setType(type);
	}
	
	public void validate(FieldPropertyResolver resolver) throws FieldValidationException {
		if(this.getField() == null) return;
		Object[] values = this.getValues();
		if(values == null) return;
		
		Node n = resolver.getNode(this.getField());
		Class<?> clazz = n.getPropertyClass();
		// validate
		for(Object object: values) {
			if(!ReflectionUtil.isSubclass(object.getClass(), clazz))
				throw new FieldValidationException(this.getField(), "wrong.type");
		}
	}

	public Object[] getValues() {
		return ProcessorUtils.getObjectValue(this, "value");
	}
	
	public Field getField() {
		return field;
	}
	public void setField(Field field) {
		this.field = field;
	}
	public T getType() {
		return type;
	}
	public void setType(T type) {
		this.type = type;
	}
	
	@Override
	public String toString() {
		return this.getType().toString();
	}
}